package com.qining618.common.interceptor;

import com.qining618.common.contants.HeaderConstants;
import com.qining618.common.enums.CallSourceEnum;
import com.qining618.common.exception.BusinessException;
import com.qining618.common.result.ErrorCode;
import com.qining618.common.utils.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author iqiao
 * @date 2018/8/17.
 */
public class HeaderParamsCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String callSource = request.getHeader(HeaderConstants.CALL_SOURCE);
//            String apiVersion = request.getHeader(HeaderConstants.API_VERSION);
            String appVersion = request.getHeader(HeaderConstants.APP_VERSION);

//            if (StringUtils.isAnyBlank(callSource, apiVersion)) {
//                throw new BusinessException(ErrorCode.PARAM_NOT_COMPLETE);
//            }

//            try {
//                Double.valueOf(apiVersion);
//            } catch (NumberFormatException e) {
//                throw new BusinessException(ErrorCode.PARAM_IS_INVALID);
//            }

            if (StringUtils.isBlank(appVersion)) {
                throw new BusinessException(ErrorCode.PARAM_NOT_COMPLETE);
            }

            if (!CallSourceEnum.isValid(callSource)) {
                throw new BusinessException(ErrorCode.PARAM_IS_INVALID);
            }

        }

        return true;
    }

}
